/**
 * File Name   : CommonService.java
 * Description : 
 */
package com.hh.admin.common.service;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.hh.common.ibatis.dao.IQueryDao;
import com.hh.common.struts.CommonActionForm;

/**
 * 公共用Service
 * @author 冯昌硕
 * @create 2013-1-20 下午2:51:43
 */
public class CommonService {

    private static final Logger log = Logger.getLogger(CommonService.class);
    
    private IQueryDao queryDao;
    
    /**
     * 公共使用的记录查询模块
     * @param form 表单数据项
     * @param sqlId 要查询的SQL ID
     * @param paramBean 查询参数方法
     * @return
     * @throws SQLException
     * @create 2013-1-20 下午3:18:16
     */
    public <T> List<T> selRecordList(CommonActionForm form, String sqlId, IBaseParamBeanOper paramBean) throws SQLException {
        List<T> resultLst = null;
        
        int currentPage = form.getCurrentPage();
        int formCurrentPage = currentPage;
        if(formCurrentPage <= 0) {
            currentPage = 1;
        }
        
        int pageSize = form.getPageSize();
        int offset = (currentPage - 1) * pageSize;
        
        paramBean.setOffset(offset);
        paramBean.setPageSize(pageSize);
        
        log.debug("开始进行分页查询：form=[" + form.getClass().getName() + "] sqlId=[" + sqlId + "] paramBean=[" + paramBean.getClass().getName() + "]");
        resultLst = queryDao.queryForObjectList(sqlId, paramBean);
        return resultLst;
    }
    
    /**
     * 查询记录数
     * @param paramObj
     * @param sqlId
     * @return
     * @create 2013-1-20 下午3:49:09
     */
    public int selRecordCount(Object paramObj, String sqlId) {
        int totleCnt = 0;
        
        try {
            Integer rs = queryDao.queryForObject(sqlId, paramObj, Integer.class);
            if(rs != null) {
                totleCnt = rs;
            }
        } catch (ClassCastException e) {
            log.error(sqlId + " 查询ClassCastException异常：" + e.toString());
            e.printStackTrace();
        } catch (SQLException e) {
            log.error(sqlId + " 查询SQLException异常：" + e.toString());
            e.printStackTrace();
        }
        
        return totleCnt;
    }

    public void setQueryDao(IQueryDao queryDao) {
        this.queryDao = queryDao;
    }
    
}
